package com.generic.mybatis.dal.interceptor.automap.builder;

import com.generic.mybatis.dal.interceptor.automap.SqlBuilder;
import com.generic.mybatis.dal.interceptor.automap.TableMapper;
import com.generic.mybatis.dal.interceptor.automap.TableMapperHolder;
import org.apache.ibatis.jdbc.SQL;
import org.apache.ibatis.mapping.MappedStatement;

import java.util.Map;

import static com.generic.mybatis.dal.interceptor.automap.builder.SqlBuilderUtil.buildCritialStatement;

/**
 * sum(字段名)
 *
 * @author wuaj
 */
public class SumBuilder implements SqlBuilder {

    @Override
    public String buildSql(MappedStatement mappedStatement, Class dtoClass, Object parameterObject) throws Exception {
        SQL sql = new SQL();
        TableMapper tableMapper = TableMapperHolder.getTableMapper(dtoClass);
        String sumField = (String) ((Map) parameterObject).get("sumField");
        String dbField = tableMapper.getPropertyAlias(sumField);
        sql.SELECT(String.format("sum(%s)", dbField));
        tableMapper.buildFromStatement(sql);
        buildCritialStatement(tableMapper, sql, parameterObject, "criterias");
        return sql.toString();
    }

}
